<template>
  <el-dialog title="编辑菜单栏" :visible.sync="open" width="500px">
    <el-form :model="formData" size="small" label-width="100px">
      <el-form-item prop="parentId" label="上级菜单">
        <el-cascader
          v-model="formData.pmenuIds"
          :options="menuList"
          collapse-tags
          clearable
          :show-all-levels="false"
          :props="{ multiple: true, value: 'menuId', label: 'menuName' }"
        ></el-cascader>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button
        type="primary"
        @click="onSubmit"
        size="small"
        :loading="Loading"
        >确定</el-button
      >
    </div>
  </el-dialog>
</template>
<script>
import { queryRoleMenus, queryAllmenus } from "@/api/userManagement/menu";
import { addAndUpdateRoleMenu } from "@/api/userManagement/roles";
import { buildtree } from "@/utils/menuFormat";
export default {
  data() {
    return {
      open: false,
      Loading: false,
      formData: {
        roleId: "",
        pmenuIds: [],
      },
      menuList: [],
    };
  },
  methods: {
    show(roleId) {
      this.open = true;
      this.formData.roleId = roleId;
      queryAllmenus({ mgrSn: this.$store.getters.mgrSn }).then((res) => {
        var menuList = [];
        buildtree(res.data.resultData, menuList, 0);
        this.menuList = menuList;
      });
      queryRoleMenus({ id: roleId }).then((res) => {
        var menuList = [];
        var pmenuIds = [];
        buildtree(res.data.resultData[0].menuList, menuList, 0);
        menuList.map((item) => {
          if (item.children) {
            var children = function (chil) {
              chil.forEach((items) => {
                pmenuIds.push([item.menuId, items.menuId]);
                if (items.children) {
                  children(items.children);
                }
              });
            };
            children(item.children);
          }
        });
        this.formData.pmenuIds = pmenuIds;
      });
    },
    filterMenu(table_list) {
      var map = [];
      table_list.forEach((item) => {
        map = map.concat(item);
      });
      var menu = [];
      for (var i = 0; i < map.length; i++) {
        if (menu.indexOf(map[i]) == -1) {
          menu.push(map[i]);
        }
      }
      return menu;
    },
    onSubmit() {
      var formData = {
        roleId: this.formData.roleId,
        pmenuIds: this.filterMenu(this.formData.pmenuIds).join(","),
      };
      this.Loading = true;
      console.log(formData);
      addAndUpdateRoleMenu(formData).then((res) => {
        this.Loading = false;
        if (res.data.resultStatus) {
          this.open = false;
          this.$message.success("新增成功");
          this.$emit("load");
        }
      });
    },
  },
};
</script>